from sqlalchemy import create_engine, Column, Integer, String, and_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote_plus




# 数据库设置
username = "root"
password = "Wb@980324"
host = "81.68.216.231"
port = 3306  # MySQL默认端口是3306
database_name = "data"
# 对密码进行URL编码
encoded_password = quote_plus(password)
# 创建数据库连接URL
database_url = f"mysql+pymysql://{username}:{encoded_password}@{host}:{port}/{database_name}"

engine = create_engine(database_url)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()


# 定义数据库表的类
class User(Base):
    __tablename__ = 'knowledge_card'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String)
    language = Column(Integer)
    standrad_interpretation = Column(String)
    popular_interpretation = Column(String)
    use_info = Column(String)
    relationship = Column(String)



Base.metadata.create_all(engine)


# 动态条件查询函数
def dynamic_query(**kwargs):
    query = session.query(User)
    filters = []
    for attr, value in kwargs.items():
        if hasattr(User, attr):
            filters.append(getattr(User, attr) == value)
    if filters:
        query = query.filter(and_(*filters))
    return query.all()


